import React, { useEffect, useState } from "react";
import { createData } from "./data";

const init = {
  count: 1,
};

const myReducer = (data, action) => {
  switch (action.type) {
    case "INCREMENT":
      return { ...data, count: data.count + 1 };
    case "DECREMENT":
      return { ...data, count: data.count - 1 };
    default:
      return data;
  }
};

const dataObject = createData(myReducer, init);

export default function GetData() {
  const [count, setCount] = useState(1);
  useEffect(() => {
    dataObject.subscribe(() => {
      const currentData = dataObject.getData();
      console.log("邹讼侠, the subscribed data is:", currentData);
      setCount(currentData.count);
    });
  }, []);

  const handdleClick = (type) => {
    dataObject.setDataByAction({ type });
  };

  return (
    <div>
      <button onClick={() => handdleClick("INCREMENT")}>按钮+</button>
      <button onClick={() => handdleClick("DECREMENT")}>按钮-</button>
      <div>index -- {count}</div>
    </div>
  );
}
